<template>
  <el-dialog v-if="load" :close-on-click-modal="false" :title="isAdd ? '添加备料计划' : '备料计划数量修改'" v-model="visible" align-center width="800px" :z-index="2000" @close="handleClose">
    <vxe-table ref="tableRef" :data="cloneData">
      <vxe-column title="备料单号" :min-width="80">
        <template #default="{ row }">
          <VSelect v-if="row.options" v-model="row.plan_no" placeholder="请选择" :options="row.options" class="w-full" />
          <div v-else>{{ row.plan_no }}</div>
        </template>
      </vxe-column>
      <vxe-column title="下单数量" :min-width="80">
        <template #default="{ row }">
          <el-input-number v-model="row.demand_num" controls-position="right" :min="0" :step="1" :precision="0" class="w-full" />
        </template>
      </vxe-column>
      <vxe-column title="操作" :min-width="80">
        <template #default="{ rowIndex }">
          <el-button v-if="cloneData.length > 1" link type="danger" @click="cloneData.splice(rowIndex, 1)">移除</el-button>
          <el-button link type="primary" @click="add">添加</el-button>
        </template>
      </vxe-column>
    </vxe-table>
    <template #footer>
      <el-button @click="close">取 消</el-button>
      <el-button type="primary" @click="submit">确 定</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import api from './api'
import XEUtils from 'xe-utils'
import { ElMessage } from 'element-plus'

const load = ref(false)
const visible = ref(false)
const form = ref({})
const cloneData = ref({})

const emit = defineEmits(['close', 'update:modelValue'])

const getPlan = async () => {
  const { sku, supplier_id, country, demand_type, sale_id } = form.value
  const res = await api.getPlan({ sku, supplier_id, country, demand_type, sale_id })
  return res.data
}

const add = async () => {
  const data = await getPlan()
  if (!data.length) {
    ElMessage.error('没有可用数据')
    return
  }
  cloneData.value.push({ ...data[0], options: data.map(d => ({ label: d.plan_no, value: d.plan_no })) })
}

// 打开弹窗
const isAdd = ref(false)
const open = async (row) => {
  console.log('row', row)
  isAdd.value = !row.plan?.length
  if (!load.value) {
    load.value = true
    await 1
  }
  form.value = row
  cloneData.value = XEUtils.clone(row.plan, true)
  visible.value = true
  if (isAdd.value) {
    add()
  }
}
// 关闭弹窗
const close = () => {
  visible.value = false
  cloneData.value = []
}

const handleClose = () => {
  emit('close')
}
// 提交
const submit = () => {
  const ids = [...new Set(cloneData.value.map(d => d.plan_no))]
  if(ids.length !== cloneData.value.length) {
    ElMessage.error('备料单号不能重复')
    return
  }
  Object.assign(form.value, { plan: XEUtils.clone(cloneData.value, true) })
  close()
}

defineExpose({ open, close })
</script>